﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Xml;

using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.Drawing.Layout;

using Elegant.Ui;

namespace iPdf
{
    class TextWatermarkPage: WatermarkPage
    {

        #region Properties
        private FontFamily WatermarkFontFamily
        {
            get
            {
                FontFamily fontFamily = null;
                if (this.FontFamily.HoveredItem != null)
                {
                    fontFamily = (FontFamily)this.FontFamily.HoveredItem;
                    return fontFamily;
                }

                fontFamily = (FontFamily)FontFamily.SelectedItem;
                return fontFamily;
            }
        }

        private float WatermarkFontSize
        {
            get
            {
                if (this.FontSize.HoveredItem != null)
                {
                    return float.Parse(this.FontSize.HoveredItem.ToString());
                }

                return float.Parse(this.FontSize.Text);
            }
        }

        private Text WaterText
        {
            get
            {
                Text waterText = new Text();
                waterText.String = this.WaterString.Text;
                if (string.IsNullOrEmpty(waterText.String))
                {
                    waterText.String = Helper.Space;
                }

                XColor color = this.WatermarkFontColor;
                waterText.Color = color;

                FontFamily family = this.WatermarkFontFamily;
                float size = this.WatermarkFontSize;
                XFontStyle style = Helper.GetAvailableFontStyle(family);
                PdfFontEmbedding fontEmbedding = (PdfFontEmbedding)this.FontEmbedding.SelectedItem;
                XPdfFontOptions fontOptions = new XPdfFontOptions(fontEmbedding);

                XFont font = null;
                try
                {
                    font = new XFont(family.Name, size, style, fontOptions);
                }
                catch
                {
                    font = new XFont(defaultFontFamily, size, style, fontOptions);
                }
                waterText.Font = font;
                
                return waterText;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Single.Parse(System.String)")]
        protected override PageOption PageOption
        {
            get
            {
                WatermarkOption option = new WatermarkOption();

                option.Element = WaterText;
                option.Layout = this.WatermarkLayout;
                return option;
            }
        }

        private XColor WatermarkFontColor
        {
            get
            {
                int alphaBlending = (int)Math.Round(this.WatermarkLayout.Opacity * byte.MaxValue);

                Color hoveredColor = this.FontColor.HoveredColor;
                if (hoveredColor != System.Drawing.Color.Empty)
                {
                    return XColor.FromArgb(alphaBlending, hoveredColor.R, hoveredColor.G, hoveredColor.B);
                }

                Color selectedColor = this.FontColor.SelectedColor;
                return XColor.FromArgb(alphaBlending, selectedColor.R, selectedColor.G, selectedColor.B);
            }
        }

        protected bool HasText
        {
            get
            {
                return this.WaterString.Enabled && !string.IsNullOrEmpty(this.WaterString.Text);
            }
        }

        public override bool ReadyToAct
        {
            get
            {
                return base.ReadyToAct && HasText;
            }
        }

        public override string IntroInfo
        {
            get
            {
                return global::iPdf.Properties.Resources.TextWatermarkPageIntroInfo;
            }
        }

        #endregion

        #region Ctor
        public TextWatermarkPage()
            : base()
        {
            actor = new TextWatermarker();
        }

        protected override void InitializeComponent()
        {
            base.InitializeComponent();

            this.TextGroup = new Elegant.Ui.RibbonGroup();
            this.WaterString = new iPdf.HoverSelectionTextBox();
            this.FontFamily = new iPdf.FontFamilyComboBox();

            this.FontInfoPanel = new Elegant.Ui.Panel();
            this.FontSize = new iPdf.FontSizeComboBox();
            this.FontColor = new iPdf.FontColorGallery();
            this.FontEmbedding = new iPdf.FontEmbeddingComboBox();
            this.LayoutGallery = new TextLayoutGallery();


            ((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.TextGroup)).BeginInit();
            this.TextGroup.SuspendLayout();
            this.FontInfoPanel.SuspendLayout();
            this.LayoutGroup.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.LayoutGallery)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.LayoutGallery.Popup)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.FontColor)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.FontColor.Popup)).BeginInit();
            this.SuspendLayout();

            this.Controls.Add(this.TextGroup);
            this.Controls.Add(this.LayoutGroup);
            this.Controls.Add(this.PreviewGroup);

            // 
            // TextGroup
            // 
            this.TextGroup.Controls.Add(this.WaterString);
            this.TextGroup.Controls.Add(this.FontFamily);
            this.TextGroup.Controls.Add(this.FontInfoPanel);
            this.TextGroup.DialogLauncherButtonVisible = false;
            this.TextGroup.Id = "41142d5a-3a6b-4a47-a1da-72ac769c80d7";
            this.TextGroup.Location = new System.Drawing.Point(4, 3);
            this.TextGroup.Name = "TextGroup";
            this.TextGroup.Size = new System.Drawing.Size(216, 94);
            this.TextGroup.SmallImages.Images.AddRange(new Elegant.Ui.ControlImage[] {
            new Elegant.Ui.ControlImage("Normal", global::iPdf.Properties.Resources.Text16)});
            this.TextGroup.TabIndex = 0;
            this.TextGroup.Text = "Text";
            // 
            // WaterString
            // 
            this.WaterString.Id = "ff4efc4c-5e24-45c5-9ec8-2fb1a3f3319b";
            this.WaterString.LabelText = "";
            this.WaterString.Location = new System.Drawing.Point(4, 2);
            this.WaterString.Name = "WaterString";
            this.WaterString.Size = new System.Drawing.Size(207, 24);
            this.WaterString.TabIndex = 1;
            this.WaterString.TextEditorWidth = 201;
            // 
            // FontFamily
            // 
            this.FontFamily.DisplayMember = "Name";
            this.FontFamily.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
            this.FontFamily.DropDownHeight = 210;
            this.FontFamily.DropDownWidth = 300;
            this.FontFamily.DroppedDown = false;
            this.FontFamily.FormatInfo = null;
            this.FontFamily.FormatString = "";
            this.FontFamily.FormattingEnabled = false;
            this.FontFamily.Id = "c413ac3f-89f2-4cbc-931c-500390089ca7";
            this.FontFamily.LabelText = "";
            this.FontFamily.Location = new System.Drawing.Point(4, 26);
            this.FontFamily.Name = "FontFamily";
            this.FontFamily.Size = new System.Drawing.Size(207, 24);
            this.FontFamily.Sorted = false;
            this.FontFamily.TabIndex = 0;
            this.FontFamily.Text = "Arial";
            this.FontFamily.TextEditorWidth = 188;
            // 
            // FontInfoPanel
            // 
            this.FontInfoPanel.Controls.Add(this.FontSize);
            this.FontInfoPanel.Controls.Add(this.FontColor);
            this.FontInfoPanel.Controls.Add(this.FontEmbedding);
            this.FontInfoPanel.Id = "1c8590e4-dd64-42fe-a8a3-dd8759bf1598";
            this.FontInfoPanel.Location = new System.Drawing.Point(3, 50);
            this.FontInfoPanel.Name = "FontInfoPanel";
            this.FontInfoPanel.Size = new System.Drawing.Size(207, 24);
            this.FontInfoPanel.TabIndex = 4;
            this.FontInfoPanel.Text = "Font Info";
            // 
            // FontSize
            // 
            this.FontSize.BackColor = System.Drawing.SystemColors.Window;
            this.FontSize.DrawMode = System.Windows.Forms.DrawMode.Normal;
            this.FontSize.DroppedDown = false;
            this.FontSize.FormatInfo = null;
            this.FontSize.FormatString = "";
            this.FontSize.FormattingEnabled = false;
            this.FontSize.Id = "d6d3fe9d-7fbc-4b17-8947-7324b1388fcf";
            this.FontSize.LabelText = "";
            this.FontSize.Location = new System.Drawing.Point(1, 0);
            this.FontSize.Name = "FontSize";
            this.FontSize.Size = new System.Drawing.Size(46, 23);
            this.FontSize.Sorted = false;
            this.FontSize.TabIndex = 2;
            this.FontSize.Text = "12";
            this.FontSize.TextEditorWidth = 27;

            // 
            // FontColor
            // 
            this.FontColor.Id = "92cca1ce-b1ec-4f2f-8f38-19ed2ee60276";
            this.FontColor.InformativenessMaximumLevel = "Elegant.Ui.GalleryInformativenessLevel:DropDownSmallImage";
            this.FontColor.ItemCategories.AddRange(new Elegant.Ui.GalleryItemCategory[] {
            new Elegant.Ui.GalleryItemCategory("Standard Colors", "Standard Colors", false, true, null)});
            this.FontColor.ItemContentPadding = new System.Windows.Forms.Padding(2);
            this.FontColor.ItemDrawMode = Elegant.Ui.GalleryItemDrawMode.OwnerDraw;
            this.FontColor.ItemHeight = 28;
            this.FontColor.ItemWidth = 28;
            this.FontColor.Location = new System.Drawing.Point(48, 0);
            this.FontColor.Name = "FontColor";
            //
            //FontColorGallery Popup
            //
            this.FontColor.Popup.PlacementMode = Elegant.Ui.PopupPlacementMode.Bottom;
            this.FontColor.Popup.Size = new System.Drawing.Size(100, 100);
            this.FontColor.PopupMinimumItemsInRowCount = 5;
            this.FontColor.PopupResizeMode = Elegant.Ui.GalleryPopupResizeMode.NoResize;
            this.FontColor.Size = new System.Drawing.Size(34, 24);
            this.FontColor.SmallImages.Images.AddRange(new Elegant.Ui.ControlImage[] {
            new Elegant.Ui.ControlImage("Normal", global::iPdf.Properties.Resources.FontColor16)});
            this.FontColor.TabIndex = 5;
            // 
            // FontEmbedding
            // 
            this.FontEmbedding.BackColor = System.Drawing.SystemColors.Window;
            this.FontEmbedding.DrawMode = System.Windows.Forms.DrawMode.Normal;
            this.FontEmbedding.DroppedDown = false;
            this.FontEmbedding.FormatInfo = null;
            this.FontEmbedding.FormatString = "";
            this.FontEmbedding.FormattingEnabled = false;
            this.FontEmbedding.Id = "7b617cbd-dded-4832-86ae-8cad45bd7a4f";
            this.FontEmbedding.InformativenessMinimumLevel = "Elegant.Ui.ComboBoxInformativenessLevel:ComboBoxWithLabel";
            this.FontEmbedding.LabelText = "Embed";
            this.FontEmbedding.Location = new System.Drawing.Point(86, 0);
            this.FontEmbedding.Name = "FontEmbedding";
            this.FontEmbedding.Size = new System.Drawing.Size(122, 23);
            this.FontEmbedding.Sorted = false;
            this.FontEmbedding.TabIndex = 6;
            this.FontEmbedding.Text = "Automatic";
            this.FontEmbedding.TextEditorWidth = 66;

            this.LayoutGroup.Controls.Add(this.LayoutGallery);
            this.LayoutGroup.Controls.SetChildIndex(this.LayoutGallery, 0);
            // 
            // LayoutGallery
            // 
            this.LayoutGallery.Id = "6f35ad47-8635-472a-98b2-9b7b2794b6e2";
            this.LayoutGallery.ItemContentBackgroundColor = System.Drawing.Color.LightSkyBlue;
            this.LayoutGallery.ItemContentPadding = new System.Windows.Forms.Padding(6);
            this.LayoutGallery.ItemHeight = 62;
            this.LayoutGallery.ItemWidth = 78;
            this.LayoutGallery.Location = new System.Drawing.Point(4, 5);
            this.LayoutGallery.MaximumItemsInRowCount = 2;
            this.LayoutGallery.MinimumItemsInRowCount = 1;
            this.LayoutGallery.Name = "LayoutGallery";
            // 
            // 
            // 
            this.LayoutGallery.Popup.PlacementMode = Elegant.Ui.PopupPlacementMode.Bottom;
            this.LayoutGallery.Popup.Size = new System.Drawing.Size(100, 100);
            this.LayoutGallery.Popup.Visible = true;
            this.LayoutGallery.PopupMinimumItemsInRowCount = 5;
            this.LayoutGallery.Size = new System.Drawing.Size(19, 66);
            this.LayoutGallery.TabIndex = 15;
            this.LayoutGallery.Text = "Text Layout Gallery";

            ((System.ComponentModel.ISupportInitialize)(this.TextGroup)).EndInit();
            this.TextGroup.ResumeLayout(false);
            this.TextGroup.PerformLayout();
            this.FontInfoPanel.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.FontColor.Popup)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.FontColor)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.LayoutGallery.Popup)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.LayoutGallery)).EndInit();
            this.LayoutGroup.ResumeLayout(false);
            this.LayoutGroup.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        #endregion

        #region Methods

        protected override void RenderPage(XGraphics gfx)
        {
            SharpHelper.AddTextToXGraphics(gfx, this.WaterText, this.WatermarkLayout);

            SharpHelper.OptimizeMemoryUsage();
        }

        protected override void  InstallEventHandlers()
        {
            base.InstallEventHandlers();

            this.FontFamily.SelectedIndexChanged += new EventHandler(WatermarkChanged);
            this.FontFamily.HoveredItemChanged += new EventHandler(WatermarkChanged);

            this.WaterString.TextChanged += new EventHandler(
                delegate(object sender, EventArgs e)
                {
                    UpdatePageOnlyControls();
                    UpdatePreviewer();
                    Global.MainWindow.UpdateActionGroup();
                });
            this.FontSize.TextEditor.TextChanged += new EventHandler(WatermarkChanged);
            this.FontSize.HoveredItemChanged += new EventHandler(WatermarkChanged);
            
            this.FontColor.SelectedColorChanged += new EventHandler(WatermarkChanged);
            this.FontColor.HoveredColorChanged += new EventHandler(WatermarkChanged);
        }


        public override void UpdatePageOnlyControls()
        {
            bool enabled = !Global.MainWindow.Busy && Global.Grid.HasItems;

            Helper.EnableControl(WaterString, enabled);
            Helper.EnableControl(this.FontFamily, enabled && HasText);
            Helper.EnableControl(this.FontInfoPanel, enabled && HasText);

            layoutGroupEnabled = enabled && HasText;
            base.UpdatePageOnlyControls();
        }

        public override void Load()
        {
            base.Load();

            FontFamily.Load();
        }

        public override void ImportSession(XmlElement sessionNode)
        {
            base.ImportSession(sessionNode);

            XmlElement markNode = (XmlElement)sessionNode.GetElementsByTagName(markTag)[0];
            this.WaterString.Text = markNode.GetAttribute(stringAttr);
            this.FontFamily.Text = markNode.GetAttribute(fontFamilyAttr);
            this.FontSize.Text = markNode.GetAttribute(fontSizeAttr);
            XColor fontColor = Helper.StringToXColor(markNode.GetAttribute(fontColorAttr));
            this.FontColor.SelectedColor = fontColor.ToGdiColor();
            PdfFontEmbedding fontEmbeddingOption =
                (PdfFontEmbedding)Enum.Parse(typeof(PdfFontEmbedding),
                markNode.GetAttribute(fontEmbeddingOptionAttr), true);
            this.FontEmbedding.SelectedItem = fontEmbeddingOption;
        }

        public override void ExportSession(System.Xml.XmlElement sessionNode)
        {
            base.ExportSession(sessionNode);

            XmlElement markNode = sessionNode.OwnerDocument.CreateElement(markTag);

            markNode.SetAttribute(stringAttr, this.WaterText.String);
            markNode.SetAttribute(fontFamilyAttr, this.WaterText.Font.FontFamily.Name);
            markNode.SetAttribute(fontSizeAttr, this.WaterText.Font.Size.ToString());
            markNode.SetAttribute(fontColorAttr, Helper.XColorToString( this.WaterText.Color));
            markNode.SetAttribute(fontEmbeddingOptionAttr, this.FontEmbedding.SelectedItem.ToString());

            sessionNode.AppendChild(markNode);
        }

        #endregion

        #region Fields
        private Elegant.Ui.RibbonGroup TextGroup;
        private iPdf.HoverSelectionTextBox WaterString;
        private FontFamilyComboBox FontFamily;
        private FontSizeComboBox FontSize;
        private Elegant.Ui.Panel FontInfoPanel;
        private FontColorGallery FontColor;
        private FontEmbeddingComboBox FontEmbedding;

        private string defaultFontFamily = "Arial";

        private string stringAttr = "String";
        private string fontFamilyAttr = "FontFamily";
        private string fontSizeAttr = "FontSize";
        private string fontColorAttr = "FontColor";
        private string fontEmbeddingOptionAttr = "Embed";


        #endregion
    }
}
